package edu.uwm.cs552;

import java.awt.Color;
import java.awt.Component;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;



public class TrainStatusPanel extends JPanel implements Observer {
	/**
	 * Keep Eclipse Happy
	 */
	private static final long serialVersionUID = 1L;
	
	private final TrainStatus train;
	private final Component[] goodPanels;

	private static Component asComponent(Good g) {
		if (g == null) return Box.createHorizontalGlue();
		return g.asLabel(false);
	}
	
	public TrainStatusPanel(TrainStatus c) {
		train = c;
		add(Box.createHorizontalGlue());
		add(new JLabel("Load:"));
		goodPanels = new Component[c.size()];
		setLayout(new BoxLayout(this,BoxLayout.LINE_AXIS));
		for (int i=0; i < c.size(); ++i) {
			goodPanels[i] = asComponent(c.getGood(i));
			add(Box.createHorizontalGlue());
			add(goodPanels[i]);
		}
		add(Box.createHorizontalGlue());
		c.addObserver(this);
		setBorder(BorderFactory.createLineBorder(Color.BLACK));
	}
	
	public void update(Observable obs, Object obj) {
		if (obs == train && obj instanceof Integer) {
			int i = ((Integer)obj).intValue();
			if (i < 0 || i >= train.size()) return;
			remove(goodPanels[i]);
			goodPanels[i] = asComponent(train.getGood(i));
			add(goodPanels[i]);
			this.validate();
		}
	}


}
